package com.sxm.yiwei.activitis;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.sxm.yiwei.MainActivity;
import com.sxm.yiwei.R;
import com.sxm.yiwei.adapters.CryHopelistAdapter;
import com.sxm.yiwei.tools.ErrType;
import com.sxm.yiwei.utils.InternetAddressUtis;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CryHopeActivity extends BaseActivity implements View.OnClickListener{

    private PullToRefreshListView pulllist;
    private ImageView cryhopeback;
    private SharedPreferences sharedPreferences;
    private String appId;
    private String userId;
    private String token;
    private int a = 1;
    private JSONArray AData;
    private List<Map<String,String>> list = new ArrayList<>();
    private HashMap<String,String>map;
    private String data;
    private CryHopelistAdapter adapter;
    private int q;
    private TextView nodata;
    private AlertDialog dialog;
    private ImageView backmain;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cry_hope);
        sharedPreferences = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        appId = sharedPreferences.getString("appid","1");
        userId = sharedPreferences.getString("userId", "0");
        token = sharedPreferences.getString("token", "2");

        initCryView();
        AlertDialog.Builder builder = new AlertDialog.Builder(CryHopeActivity.this,R.style.NoBackGroundDialog);
        View view = LayoutInflater.from(CryHopeActivity.this).inflate(R.layout.progress_dialog, null);
        ProgressBar diapro = (ProgressBar) view.findViewById(R.id.pro_dia);
        builder.setView(view);
        dialog = builder.create();
        dialog.show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                getHope(String.valueOf(a));
            }
        }).start();

    }
        // 获取红包列表
    private void getHope(String s) {

        RequestParams params = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.HOPE_GETHOPE_BOOK);
        params.addHeader("Content-Type","application/json");
        params.addHeader("token",token);
        params.addHeader("appId",appId);
        params.addHeader("userId",userId);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("pageNo",String.valueOf(a));
        jsonObject.put("pageSize","20");
        params.addParameter("params",jsonObject.toJSONString());
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                dialog.dismiss();
                getHopeData(result);

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ErrType.errType(CryHopeActivity.this,ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
        //获取信息列表
    private void getHopeData(String result) {

        com.alibaba.fastjson.JSONObject obj = JSON.parseObject(result);
        data = obj.getString("data");
        AData = JSONArray.parseArray(data);
        for (int i = 0; i < AData.size(); i++) {
            map = new HashMap();
            com.alibaba.fastjson.JSONObject obj1 = JSON.parseObject(String.valueOf(AData.get(i)));
            String avatar = obj1.getString("avatar");
            final String id = obj1.getString("id");
            String imageUrl = obj1.getString("imageUrl");
            String type = obj1.getString("type");
            String wish = obj1.getString("wish");
            map.put("avatar", avatar);
            map.put("imageUrl", imageUrl);
            map.put("type", type);
            map.put("wish", wish);
            map.put("id", id);
            list.add(map);
            adapter = new CryHopelistAdapter(CryHopeActivity.this, list);
            pulllist.setAdapter(adapter);
            // 设置lisview 的 item 点击事件
            // 设置刷新
            adapter.setOnClickListenerItem(new CryHopelistAdapter.OnClickListenerItem() {
                @Override
                public void OnClickListenerImg(int position) {
                    HashMap<String, String> item = (HashMap<String, String>) adapter.getItem(position);
                    String id1 = item.get("id");
                    Intent in = new Intent(CryHopeActivity.this, CryHopeContentActivity.class);
                    in.putExtra("id", id1);
                    startActivity(in);
                }

                @Override
                public void OnClickListenerButton(int position) {
                    HashMap<String, String> item = (HashMap<String, String>) adapter.getItem(position);
                    String id1 = item.get("id");
                    // refresh();
                    Intent in = new Intent(CryHopeActivity.this, CryHopeContentActivity.class);
                    in.putExtra("id", id1);
                    startActivity(in);
                }
            });
            adapter.notifyDataSetChanged();


            pulllist.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
            ListView refreshableView = pulllist.getRefreshableView();
            refreshableView.setSelection(10*a);
            pulllist.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
                @Override
                public void onRefresh(PullToRefreshBase<ListView> refreshView) {

                    a++;
                    getHope(String.valueOf(a));
                    new FinishRefresh().execute();
                    adapter.notifyDataSetChanged();

                }
            });
        }
    }

        //初始化控件
    private void initCryView() {
        pulllist = (PullToRefreshListView) findViewById(R.id.cry_hopelist);
        cryhopeback = (ImageView) findViewById(R.id.cry_hope_back);
        nodata = (TextView) findViewById(R.id.cry_nodata);
        backmain = (ImageView) findViewById(R.id.cryhope_backmain);
        backmain.setOnClickListener(this);
        cryhopeback.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.cry_hope_back:
                finish();
                break;
            case R.id.cryhope_backmain:
                startActivity(new Intent(CryHopeActivity.this, MainActivity.class));
                AppManager.getAppManager().finishAllActivity();
                break;
        }
    }

    private class FinishRefresh extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {

            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {

            adapter.notifyDataSetChanged();
            pulllist.onRefreshComplete();
        }
    }
}
